import { api } from './apiClient'
import type { Attachment, Note, NoteGroup } from '@/types/notes'

type ApiResp<T> = { success: boolean; data: T; message?: string }

export const notesApi = {
  // Groups
  async listGroups(): Promise<NoteGroup[]> {
    const { data } = await api.get<ApiResp<NoteGroup[]>>('/notes/groups')
    return data.data
  },
  async createGroup(name: string): Promise<NoteGroup> {
    const { data } = await api.post<ApiResp<NoteGroup>>('/notes/groups', { name })
    return data.data
  },
  async renameGroup(id: string, name: string): Promise<NoteGroup> {
    const { data } = await api.patch<ApiResp<NoteGroup>>(`/notes/groups/${id}`, { name })
    return data.data
  },
  async deleteGroup(id: string): Promise<void> {
    await api.delete(`/notes/groups/${id}`)
  },

  // Notes
  async listNotes(groupId?: string | 'all'): Promise<Note[]> {
    const qs = groupId && groupId !== 'all' ? `?groupId=${encodeURIComponent(groupId)}` : ''
    const { data } = await api.get<ApiResp<Note[]>>(`/notes${qs}`)
    return data.data
  },
  async createNote(input: Partial<Note>): Promise<Note> {
    const payload = {
      title: input.title ?? '',
      content: input.content ?? '',
      groupId: input.groupId ?? null,
      reminderAt: input.reminderAt ?? null,
    }
    const { data } = await api.post<ApiResp<Note>>('/notes', payload)
    return data.data
  },
  async updateNote(id: string, patch: Partial<Note>): Promise<Note> {
    const { data } = await api.patch<ApiResp<Note>>(`/notes/${id}`, patch)
    return data.data
  },
  async deleteNote(id: string): Promise<void> {
    await api.delete(`/notes/${id}`)
  },
  async addTime(id: string, seconds: number): Promise<{ id: string; timeSpent: number }> {
    const { data } = await api.post<ApiResp<{ id: string; timeSpent: number }>>(`/notes/${id}/time`, { seconds })
    return data.data
  },

  // Attachments
  async uploadAttachment(noteId: string, file: File, kind: Attachment['kind'] = 'file'): Promise<Attachment> {
    const form = new FormData()
    form.append('file', file)
    form.append('kind', kind)
    const { data } = await api.post<ApiResp<Attachment>>(`/notes/${noteId}/attachments`, form, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    return data.data as Attachment
  },
  async listAttachments(noteId: string): Promise<Attachment[]> {
    const { data } = await api.get<ApiResp<Attachment[]>>(`/notes/${noteId}/attachments`)
    return data.data
  },
  async deleteAttachment(attachmentId: string): Promise<void> {
    await api.delete(`/notes/attachments/${attachmentId}`)
  },
}